﻿using System;
using System.Collections.Generic;
using System.Text;

namespace UDS.Build.Database.Replication
{
    class PublishedTableDefinition
    {
        private string version;
        private string tableName;
        private string schemaOption;
        private PublicationPublishedTableArticleColumn[] pkColumns;
        private PublicationPublishedTableArticleColumn[] columns;

        private void PrepareColumns(PublicationPublishedTable table)
        {
            // Order columns based on ColumnOrder field
            List<PublicationPublishedTableArticleColumn> cols = new List<PublicationPublishedTableArticleColumn>();
            if (table.ArticleColumn != null)
            {
                cols.AddRange(table.ArticleColumn);
            }
            cols.Sort(
                // anonymous delegate
                delegate(PublicationPublishedTableArticleColumn x, PublicationPublishedTableArticleColumn y)
                {
                    return x.ColumnOrder - y.ColumnOrder;
                }
            );
            columns = cols.ToArray();
            List<PublicationPublishedTableArticleColumn> pks = new List<PublicationPublishedTableArticleColumn>();
            for (int i = 0; i < columns.Length; i++)
            {
                PublicationPublishedTableArticleColumn col = columns[i];
                // Replace ColumnOrder with column index
                col.ColumnOrder = i + 1;
                if (col.IsPartOfPK == 1)
                {
                    pks.Add(col);
                }
            }
            pkColumns = pks.ToArray();
        }

        public PublishedTableDefinition(string version, PublicationPublishedTable table)
        {
            this.tableName = table.TableName;
            this.version = version;
            this.schemaOption = table.schemas_option;
            // Skip deleted tables
            if (table.Operation == 1)
            {
                PrepareColumns(table);
            }
        }

        public string Version
        {
            get
            {
                return version;
            }
        }

        public string Name
        {
            get
            {
                return tableName;
            }
        }

        public string SchemaOption
        {
            get
            {
                return schemaOption;
            }
        }

        public PublicationPublishedTableArticleColumn[] Columns
        {
            get
            {
                return columns;
            }
        }

        public PublicationPublishedTableArticleColumn[] PKColumns
        {
            get
            {
                return pkColumns;
            }
        }
    }
}
